import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { LibAppView } from "../../../../lib";
import { App, Button, Switch, Input, Modal } from "antd";
import { FormattedMessage, useIntl } from "react-intl";
import { ResourceList } from "../../Component/ResourceList";
import styles from "./styles.module.scss";
import { isEmpty } from "@/lib/utils";
import { PlusOutlined } from "@ant-design/icons";
import { useDelete } from "../../hooks/useDelete";
import { AdminRight } from "@/pages/Admin/data/AdminPageAuth";

const UserGroupList = LibAppView.withService({
    reqEndPoints: [{
        endPoint: "user.groupList",
        name: "groupList"
    }]
})((props) => {
    const intl = useIntl();
    const app = LibAppView.useMicroApp();
    const { message, modal } = App.useApp();

    const [ groupName, setGroupName ] = useState("");
    const [ showInput, setShowInput ] = useState(false);
    const [ confirmLoading, setConfirmLoading ] = useState(false);
    const listRef = useRef<any>();
    const deleteAction = useDelete({
        endPoint: "user.groupSubmit",
        cancelEndPoint: "user.groupSubmit",
        data: {},
        listRef
    });

    const SearchFields: Admin.IAdvancedField[] = [
        {
            type: "Input",
            label: "admin.pages.user.group.list.name",
            name: "name",
            placeholder: "admin.layout.input.placeholder",
            props: { autoComplete: "off" }
        },
        {
            type: "Input",
            label: "admin.pages.user.group.list.title",
            name: "title",
            placeholder: "admin.layout.input.placeholder",
            props: { autoComplete: "off" }
        }
    ];
   

    const columns = useMemo(() =>([
        {
            title: <FormattedMessage id="admin.pages.user.group.list.title"/>,
            dataIndex: "name",
            width: 120,
            fixed: true
        },{
            title: <FormattedMessage id="admin.pages.user.list.status"/>,
            dataIndex: "status",
            width: 80,
            render: (status: number, data: any) => {
                return <AdminRight authRight="editable" mode="disabled"><Switch
                    checkedChildren={<FormattedMessage id="admin.pages.operate.enabled"/>}
                    unCheckedChildren={<FormattedMessage id="admin.pages.operate.disabled"/>}
                    checked={status == 1}
                    onChange={(checked) => {
                        listRef.current.showLoading();
                        props.withServiceApi.send({
                            endPoint: "user.groupSubmit",
                            data: {
                                ...data,
                                status: checked ? 1 : 0
                            }
                        }).then(() => {
                            listRef.current.refreshData();
                        }).catch((err) => {
                            listRef.current.hideLoading();
                            message.error(err.message || "未知错误");
                            console.error(err);
                        });
                    }}
                /></AdminRight>
            }
        }, {
            title: <FormattedMessage id="admin.pages.createUser"/>,
            dataIndex: "createUserName",
            width: 100
        },{
            title: <FormattedMessage id="admin.pages.createTime"/>,
            dataIndex: "createDateTime",
            width: 180
        },{
            title: <FormattedMessage id="admin.pages.updateUser"/>,
            dataIndex: "updateUserName",
            width: 100
        }, {
            title: <FormattedMessage id="admin.pages.updateTime"/>,
            dataIndex: "updateDateTime",
            width: 180
        },{
            title: <FormattedMessage id="admin.pages.language.operate"/>,
            dataIndex: "id",
            render: (id: number, data: any) => {
                return (<div className={styles.tableOperate}>
                    <AdminRight authRight="editable" mode="disabled">
                        <Button type="primary" size="small" onClick={() => {
                            app.startJourney("userGroupManagement", { state: data });
                        }}>
                            <FormattedMessage id="admin.pages.operate.edit"/>
                        </Button>
                    </AdminRight>
                    <AdminRight authRight="deleteable" mode="disabled">
                        <Button size="small" onClick={() => {
                            deleteAction.delete({
                                ...data,
                                status: -1
                            });
                        }}>
                            <FormattedMessage id="admin.pages.operate.delete"/>
                        </Button>
                    </AdminRight>
                </div>);
            }
        }
    ]),[app]);

    const onCreateGroup = useCallback(() => {
        if(isEmpty(groupName)) {
            message.error("请输入用户组名称");
            return;
        }
        setConfirmLoading(true);
        props.withServiceApi.send({
            endPoint: "user.groupSubmit",
            data: {
                name: groupName,
                status: 1
            }
        }).then((resp: any) => {
            setConfirmLoading(false);
            setShowInput(false);
            app.startJourney("userGroupManagement", {
                state: resp.data || {}
            });
        }).catch((err) => {
            setConfirmLoading(false);
            message.error(err.message || "未知错误");
            console.error(err);
        });
    }, [groupName]);
    const listEndPoint = useMemo(() => ({
        endPoint: "user.groupList"
    }), []);

    const Operator = useMemo(() => {
        return () => {
            return (<AdminRight authRight="editable" mode="disabled">
                <Button type="primary" onClick={() => {
                    setShowInput(true);
                }}>
                    <PlusOutlined />
                    <span><FormattedMessage id="admin.pages.operate.add" /></span>
                </Button>
            </AdminRight>);
        }
    }, []);
    useLayoutEffect(() => {
        app.registeJourney({
            name: "userGroupManagement",
            title: "",
            stepJourney: true,
            isTempJourney: true,
            steps: [
                {
                    "page": "admin.editUserGroup",
                    "isMemoryPage": true
                }
            ]
        });
    }, []);
   
    return (
    <>
        <ResourceList
            refApi={listRef}
            tableColumns={columns}
            searchFields={SearchFields} 
            listEndPoint={listEndPoint}
            Operators={Operator}
        />
        <Modal
                title="添加用户组"
                open={showInput}
                onCancel={() => setShowInput(false)}
                onOk={onCreateGroup}
                confirmLoading={confirmLoading}
            >
                <Input placeholder="请输入用户组名称" onChange={(e) => setGroupName(e.target.value)}/>
            </Modal>
    </>
  
    );
});

export default UserGroupList;
